package com.ruoyi.web.controller.tool;

import java.io.File;
import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.system.domain.Mp3record;
import com.ruoyi.system.domain.Mp3recordExample;
import com.ruoyi.system.mapper.Mp3recordMapper;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import us.codecraft.xsoup.Xsoup;

/**
 * swagger 用户测试方法
 *
 * @author ruoyi
 */
@Api("用户信息管理")
@RestController
@RequestMapping("/test/user")
public class TestController extends BaseController {
    private final static Map<Integer, UserEntity> users = new LinkedHashMap<Integer, UserEntity>();

    {
        users.put(1, new UserEntity(1, "admin", "admin123", "15888888888"));
        users.put(2, new UserEntity(2, "ry", "admin123", "15666666666"));
    }

    @Autowired
    private Mp3recordMapper mp3recordMapper;

    @ApiOperation("获取用户列表")
    @GetMapping("/list")
    public AjaxResult userList() {
        List<UserEntity> userList = new ArrayList<UserEntity>(users.values());
        return AjaxResult.success(userList);
    }

    @ApiOperation("获取用户详细")
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path")
    @GetMapping("/{userId}")
    public AjaxResult getUser(@PathVariable Integer userId) {
        if (!users.isEmpty() && users.containsKey(userId)) {
            return AjaxResult.success(users.get(userId));
        } else {
            return error("用户不存在");
        }
    }

    @ApiOperation("新增用户")
    @ApiImplicitParam(name = "userEntity", value = "新增用户信息", dataType = "UserEntity")
    @PostMapping("/save")
    public AjaxResult save(UserEntity user) {
        if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) {
            return error("用户ID不能为空");
        }
        return AjaxResult.success(users.put(user.getUserId(), user));
    }

    @ApiOperation("新增用户xxxxxx")
    @ApiImplicitParam(name = "userEntity", value = "新增用户信息", dataType = "UserEntity")
    @PostMapping("/testMap")
    @ResponseBody
    public AjaxResult testMap(@RequestBody() Map<String, Object> map) {
        Object name = map.get("name");
        String nameStr = (String) name;
        System.out.println("nameStr = " + nameStr);

        Object list1Obj = map.get("list1");
        Object list2Obj = map.get("list2");
        Object list3Obj = map.get("list3");
//        LinkedHashMap nameList1 = (LinkedHashMap) nameListObj;
//        ArrayList nameList2 = (ArrayList) nameListObj;
//        LinkedList nameList3 = (LinkedList) nameListObj;
////        ArrayList nameList2 = (ArrayList) nameListObj;

//        if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) {
//            return error("用户ID不能为空");
//        }
        return AjaxResult.success(map);
    }

    @ApiOperation("更新用户")
    @ApiImplicitParam(name = "userEntity", value = "新增用户信息", dataType = "UserEntity")
    @PutMapping("/update")
    public AjaxResult update(UserEntity user) {
        if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) {
            return error("用户ID不能为空");
        }
        if (users.isEmpty() || !users.containsKey(user.getUserId())) {
            return error("用户不存在");
        }
        users.remove(user.getUserId());
        return AjaxResult.success(users.put(user.getUserId(), user));
    }

    @ApiOperation("删除用户信息")
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path")
    @DeleteMapping("/{userId}")
    public AjaxResult delete(@PathVariable Integer userId) {
        if (!users.isEmpty() && users.containsKey(userId)) {
            users.remove(userId);
            return success();
        } else {
            return error("用户不存在");
        }
    }

    @Value("#{T(cn.hutool.core.io.FileUtil).readUtf8String('E:\\\\work\\\\SmartCRM\\\\project\\\\trunk\\\\webserviceTest\\\\src\\\\com\\\\dcits\\\\crm\\\\common\\\\webservice\\\\oaForCrm20201214\\\\GetJinPingMei.json')}")
    public String jsonStr;

    @ApiOperation("urlTest")
    @GetMapping("/urlTest")
    public String urlTest() {
//        String jsonStr = FileUtil.readUtf8String("E:\\work\\SmartCRM\\project\\trunk\\webserviceTest\\src\\com\\dcits\\crm\\common\\webservice\\oaForCrm20201214\\GetJinPingMei.json");



        JSONArray jsonArray = JSONUtil.parseArray(jsonStr);

        Mp3recordExample example = new Mp3recordExample();
        Mp3recordExample.Criteria criteria = example.createCriteria();
        criteria.andMp3IsExistsEqualTo("0");
        criteria.andContentUrlIsNull();
        List<Mp3record> mp3NotExistrecords = mp3recordMapper.selectByExample(example);

        for (Object jsonObj : jsonArray) {
            JSONObject jsonObjOne = (JSONObject) jsonObj;
            JSONArray listArray = jsonObjOne.getJSONArray("list");

            for (Object o: listArray) {
                JSONObject jsonObjTwo = (JSONObject) o;
                JSONObject appMsgExtInfo = jsonObjTwo.getJSONObject("app_msg_ext_info");
                String appMsgExtInfoTitle = appMsgExtInfo.getStr("title");
                for (Mp3record record : mp3NotExistrecords) {
                    if (appMsgExtInfoTitle.equals(record.getTittle())) {
                        record.setContentUrl(appMsgExtInfo.getStr("content_url"));
                    }
                }

                JSONArray multiAppMsgItemList = appMsgExtInfo.getJSONArray("multi_app_msg_item_list");
                if (multiAppMsgItemList == null) {
                    appMsgExtInfo.set("multi_app_msg_item_list", "null");
                }
                JSONArray needDelJsonArray = new JSONArray();
                for (Object o1 : multiAppMsgItemList) {
                    JSONObject jsonObjThr = (JSONObject) o1;
                    String title = jsonObjThr.getStr("title");
                    for (Mp3record record : mp3NotExistrecords) {
                        if (title.equals(record.getTittle())) {
                            record.setContentUrl(jsonObjThr.getStr("content_url"));
                        }
                    }
                }

            }

        }
        mp3recordMapper.updateBatchSelective(mp3NotExistrecords);
        return "生成json成功";
    }

    /**
     * 功能描述: 剩余的676个自己解析
     * @param
     * @return: java.lang.String
     * @Author: zhangTao
     * @Date: 2021/3/18 0018 13:58
    */
    @ApiOperation("urlGetMp3Test")
    @GetMapping("/urlGetMp3Test")
    public String urlGetMp3Test() {
        String downloadPath = "E:\\work\\GitHubs\\RuoYi\\ruoyi-admin\\src\\main\\resources\\";
        Mp3recordExample example = new Mp3recordExample();
        Mp3recordExample.Criteria criteria = example.createCriteria();
        criteria.andMp3IsExistsEqualTo("0");
        criteria.andContentUrlIsNotNull();
        List<Mp3record> mp3NotExistrecords = mp3recordMapper.selectByExample(example);
        for (Mp3record record : mp3NotExistrecords) {
            String contentUrl = record.getContentUrl();
            String newContentUrl = "";
            if (contentUrl.startsWith("http://")) {
                newContentUrl = contentUrl.replaceAll("http://", "https://");
            }
            String resultStr = HttpUtil.get(newContentUrl);

            Document documents = Jsoup.parse(resultStr);
            Elements mpvoiceEle = documents.getElementsByAttribute("voice_encode_fileid");
            String voice_encode_fileid = mpvoiceEle.attr("voice_encode_fileid");
            String mp3Name = record.getMp3NewName();

//        https://res.wx.qq.com/voice/getvoice?mediaid=Mzg5MTE0OTgxMF8yMjQ3NDk1OTY4
            if (StrUtil.isNotBlank(voice_encode_fileid)) {
                HttpUtil.downloadFile("https://res.wx.qq.com/voice/getvoice?mediaid="+voice_encode_fileid,downloadPath+mp3Name);
            }
            if (new File(downloadPath + mp3Name).exists()) {
                record.setMp3IsExists("1");
            }
        }
        mp3recordMapper.updateBatchSelective(mp3NotExistrecords);

        return "下载 完成";
    }
    /**
     * 功能描述: 剩余的676个自己解析
     * @param
     * @return: java.lang.String
     * @Author: zhangTao
     * @Date: 2021/3/18 0018 13:58
    */
    @ApiOperation("urlGetMp3OneTest")
    @GetMapping("/urlGetMp3OneTest")
    public String urlGetMp3OneTest() {
        String downloadPath = "E:\\work\\GitHubs\\RuoYi\\ruoyi-admin\\src\\main\\resources\\";
        String urlString = "https://mp.weixin.qq.com/s?__biz=Mzg5MTE0OTgxMA==&amp;mid=2247495974&amp;idx=3&amp;sn=0cd19dae5758d32b9098e89d29eb8bbd&amp;chksm=cfd37dbbf8a4f4ad5b7a2437015400ad563b42c8d8c56959fdbe96543d41425fb58a257a2fdd&amp;scene=27#wechat_redirect";
        if (urlString.startsWith("http://")) {
            urlString.replaceAll("http://", "https://");
        }
        String contentStr = HttpUtil.get(urlString);

        Document documents = Jsoup.parse(contentStr);
        Elements mpvoiceEle = documents.getElementsByAttribute("voice_encode_fileid");
        String voice_encode_fileid = mpvoiceEle.attr("voice_encode_fileid");
        String mp3Name = mpvoiceEle.attr("name");

//        https://res.wx.qq.com/voice/getvoice?mediaid=Mzg5MTE0OTgxMF8yMjQ3NDk1OTY4
        HttpUtil.downloadFile("https://res.wx.qq.com/voice/getvoice?mediaid="+voice_encode_fileid,downloadPath+mp3Name);
        if (new File(downloadPath + mp3Name).exists()) {

        }
        return "下载 完成";
    }

//        String tittle = Xsoup.compile("//mpvoice[@id=\"activity-name\"]/text()").evaluate(documents).get();
//        String voice_encode_fileid = Xsoup.compile("//mpvoice@voice_encode_fileid").evaluate(documents).get();
//        String mp3Name = Xsoup.compile("//mpvoice@name").evaluate(documents).get();


    @ApiOperation("xpathTest")
    @GetMapping("/xpathTest")
    public String xpathTest() {

//        final ArrayList<Mp3record> mp3records = new ArrayList<>();
        String dicPath = "D:\\WeChatDownload v20200520\\application\\说书的小马哥\\";
        final SuffixFileFilter fileFilter = new SuffixFileFilter("html");
        final List<File> files = FileUtil.loopFiles(dicPath, fileFilter);
//        final List<File> collect = files.stream().limit(10).collect(Collectors.toList());
        for (File file : files) {
            final String htmls = FileUtil.readUtf8String(file);
            Document documents = Jsoup.parse(htmls);
            //文件名(Mzg5MTE0OTgxMF8yMjQ3NDk5NTE0.mp3)
            final String mp3Name = StrUtil.subSufByLength(htmls.split(".mp3")[0], 28) + ".mp3";

            final File mp3file = new File(dicPath + mp3Name);
            final boolean exists = mp3file.exists();
            //如果mp3文件存在则更新
            final String newName = file.getName().replace("html", "");
            if (exists) {

                FileUtil.rename(mp3file, newName, true, true);
            }
            //标题
            String tittle = Xsoup.compile("//*[@id=\"activity-name\"]/text()").evaluate(documents).get();
            final String htmlName = file.getName();
            final Mp3record mp3record = new Mp3record();
            String existsStr = "";
            if (exists) {
                existsStr = "1";
            }else {
                existsStr = "0";
            }

            mp3record.setHtmlName(htmlName);
            mp3record.setTittle(tittle);
            mp3record.setMp3IsExists(existsStr);
            mp3record.setMp3OldName(mp3Name);
            mp3record.setMp3NewName(newName+"mp3");
            mp3record.setUpdateTime(LocalDateTime.now());
            mp3recordMapper.insert(mp3record);
        }
        return "进行完成";
    }




}

@ApiModel("用户实体")
class UserEntity {
    @ApiModelProperty("用户ID")
    private Integer userId;

    @ApiModelProperty("用户名称")
    private String username;

    @ApiModelProperty("用户密码")
    private String password;

    @ApiModelProperty("用户手机")
    private String mobile;

    public UserEntity() {

    }

    public UserEntity(Integer userId, String username, String password, String mobile) {
        this.userId = userId;
        this.username = username;
        this.password = password;
        this.mobile = mobile;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
}
